//
//  NSObject+additions.m
//  Tool
//
//  Created by ZJ on 17/2/15.
//  Copyright © 2017年 ZJ. All rights reserved.
//

#import "NSObject+additions.h"

@implementation NSObject (additions)

- (NSString *)jsonStringFromObject:(id)object { //OC对象转JSON
    NSError *erro = nil;
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&erro];
    NSString *jsonString = [[NSString alloc]initWithData:jsondata encoding:NSUTF8StringEncoding];
    return jsonString;
}


//把jsonString转换成任意对象
- (id)jsonStringToObject:(NSString *)jsonString
{
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    if (!data) {
        return nil;
    }
    NSError *error;
    id object = [NSJSONSerialization JSONObjectWithData:data
                 
                                                options:NSJSONReadingAllowFragments
                 
                                                  error:&error];
    if(error) {
        
        NSLog(@"json解析失败：%@",error);
        return nil;
    }
    return object;
}

#pragma mark - 寻找最上层控制器 
/** 寻找最上层控制器 */
- (UIViewController *)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:nav.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}


#pragma mark -  判断文件是否已经在沙盒中已经存在
- (BOOL) isFileExist:(NSString *)fileName
{
    ///cache文件夹
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    ///document文件
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
//    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    return result;
}
@end
